package com.victor.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.victor.entity.tags.TagsBack;

public class TagsUtils {
	/**
	 * Post请求获取标签
	 * 
	 * @param title
	 * @return
	 * @throws Exception
	 */
	public static String httpSend(String title) throws Exception {
		// 发送参数
		URL url = new URL("https://wenda.so.com/engine/getAskTags");
		Map<String, Object> params = new LinkedHashMap<>();
		params.put("title", title);

		// 开始访问
		StringBuilder postData = new StringBuilder();
		for (Map.Entry<String, Object> param : params.entrySet()) {
			if (postData.length() != 0)
				postData.append('&');
			postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
			postData.append('=');
			postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
		}
		byte[] postDataBytes = postData.toString().getBytes("UTF-8");

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
		conn.setRequestProperty("CURLOPT_HTTPHEADER", "'X-AjaxPro-Method:ShowList','User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36'");
		conn.setDoOutput(true);
		conn.getOutputStream().write(postDataBytes);

		Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

		StringBuilder sb = new StringBuilder();

		for (int c; (c = in.read()) >= 0;)
			sb.append((char) c);
		String response = sb.toString();
//		System.out.println(response);

		return response;
	}


	public static void main(String[] args) throws Exception {
		String title = "本田";
		String retAskTags = httpSend(title);
		TagsBack t = JSONObject.parseObject(retAskTags,TagsBack.class);
		System.out.println(t.getResult().getTags());
	}
}
